<template>
	<view class="content">
		<view class="sb-info">
			设备名称：{{name}}/{{sbClientid}}
		</view>
		<view class="wifi-box" @click="showWifi">
			<view class="wifi-l">
				<image src="/static/images/wifi.png" mode="widthFix"></image>
				<!-- <image src="/static/images/wifi1.png" mode="widthFix"></image> -->
				<view class="wifi-text">
					<text>WI-FI连接</text>
					<text>连接WI-FI网络</text>
				</view>
			</view>
			<image class="jt-icon" src="/static/images/icon1.png" mode="widthFix"></image>
		</view>
		<text>项目配置</text>
		<view class="pro-box">
			<view :class="isGl==item.id?'active pro-item':'pro-item'" v-for="item in typeData" @click="editItem(item)">
				<image :src="'/static/images/item'+item.id+'.png'" mode="widthFix"></image>
				<text>{{item.xmMc}}</text>
			</view>
		</view>
		<view class="set-box">
			<view class="set-item" @click="gotoPage('/pages/index/align?name='+name+'&ip='+sbIp+'&pid='+isGl)">
				<image v-if="sbIszx=='1'" src="/static/images/icon4.png" mode="widthFix"></image>
				<image v-else src="/static/images/icon13.png" mode="widthFix"></image>
				<text>校准画面</text>
			</view>
			<view class="set-item" @click="startBtn">
				<image v-if="sbIszx=='1'" src="/static/images/icon5.png" mode="widthFix"></image>
				<image v-else src="/static/images/icon7.png" mode="widthFix"></image>
				<text>连接设备</text>
			</view>
			<view class="set-item" @click="gotoPage('/pages/index/firmware?sbClientid='+sbClientid+'&isbIp='+sbIp)">
				<image v-if="sbIszx=='1'" src="/static/images/icon15.png" mode="widthFix"></image>
				<image v-else src="/static/images/icon16.png" mode="widthFix"></image>
				<text>固件升级</text>
			</view>
		</view>
		
		<!-- 弹窗 -->
		<wifiSet ref="wifiSet" @getwifiInfo="getwifiInfo"></wifiSet>
		<unbind ref="unbind" :eqId="eqId" @bindChange="bindChange"></unbind>
	</view>
</template>

<script>
	import wifiSet from '../../components/wifiSet.vue'
	import unbind from '../../components/unbind.vue'
	export default {
		components:{wifiSet,unbind},
		data() {
			return {
				name:'',
				typeData:[],
				eqId:'',
				isGl:'',
				sbIp:'',
				sbIszx:'',
				qid:'',
				nmn:'',
				ips:'',
				sbClientid:'',
				device: {
					deviceId: "",
					name: "",
				},
				uuid: {
					deviceId: '',
					serviceId: '',
					writeId: '',
					notifyId: ''
				},
				getdata:'',
			}
		},
		onLoad(options) {
			this.name=options.name
			this.eqId = options.id
			this.getlist()
			this.getTc()
			this.getFw()
		},
		onShow() {
			
		},
		onUnload() {
			this.cancelConcent()
			uni.stopBluetoothDevicesDiscovery({
				success(res) {
					// console.log('连接蓝牙成功之后关闭蓝牙搜索');
				}
			})
		},
		methods:{
			// 打开蓝牙适配器
			initBlue() {
				let that = this
				uni.openBluetoothAdapter({
					success(res) {
						console.log('打开蓝牙适配器成功');
						if(that.sbIszx!=='1'){
							that.findBlue()
						}
						// that.connetBlue(that.device.deviceId)
					},
					fail() {
						console.log('打开蓝牙适配器失败');
						uni.showToast({
							title: '请打开蓝牙',
							type: 'error',
							icon: 'none'
						})
					}
				})
			},
			// 搜索周边设备
			findBlue() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: false,
					interval: 0,
					success(res) {
						console.log('设备搜索中');
						uni.onBluetoothDeviceFound(devices => {
							that.getBlue()
						})
					},
					fail() {
						console.log('设备搜索失败');
						uni.showToast({
							icon: 'none',
							title: '无法获取'
						})
					}
				})
			},
			// 获取搜索到的设备信息
			getBlue() {
				let that = this
				that.listShow = !that.listShow
				uni.getBluetoothDevices({
					success(res) {
						console.log(res)
						uni.showLoading({
							title: '蓝牙匹配中'
						});
						res.devices.map(item=>{
							const originalStr = item.localName;
							const result = originalStr.replace(/-.*/, '');
							console.log(result)
							if(result == that.sbClientid){
								uni.hideLoading();
								that.connetBlue(item)
							}else{
								uni.hideLoading();
								that.toast('匹配失败')
							}
						})
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '无法获取'
						})
					}
				})
			},
			//连接蓝牙
			connetBlue(item) {
				console.log(item)
				let that = this;
				that.device = item
				uni.createBLEConnection({
					deviceId: item.deviceId, //设备id
					async success(res) {
						console.log("连接蓝牙成功", res)
						uni.showToast({
							title: '连接中',
							icon: 'loading',
							duration: 2000
						})
						let res1 = await that.http('post','/tc/tcOperate/upSBB',{uuid:item.deviceId,clientid:that.sbClientid})
						if(res1.code==200){
							console.log(res1)
						}
						uni.stopBluetoothDevicesDiscovery({
							success(res) {
								// console.log('连接蓝牙成功之后关闭蓝牙搜索');
							}
						})
						that.getServiceId(that.device)
					},
					fail() {
						console.log("连接蓝牙失败!-->11111")
					}
				})
			},
			// 获取蓝牙设备服务
			getServiceId(item) {
				let deviceId = item.deviceId
				let that = this
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: deviceId,
						success(res) {
							console.log(res)
							if (res.services.length == 0) {
								uni.showToast({
									icon: 'none',
									title: '设备不可用',
									duration: 1000
								})
							} else {
								that.uuid.deviceId = deviceId
								that.uuid.serviceId = '0000AE30-0000-1000-8000-00805F9B34FB'
								that.getCharacteId(that.uuid)
							}
						},
						fail() {
							uni.showToast({
								icon: 'none',
								title: '获取服务失败'
							})
						}
					})
				}, 1000)
			},
			// 获取蓝牙特征值
			getCharacteId(item) {
				let that = this
				uni.getBLEDeviceCharacteristics({
					deviceId: item.deviceId,
					serviceId: item.serviceId,
					success(res) {
						console.log('获取蓝牙特征值', res)
						that.uuid.writeId = '0000AE01-0000-1000-8000-00805F9B34FB'
						that.uuid.notifyId = '0000AE02-0000-1000-8000-00805F9B34FB'
						that.uuid.deviceId = item.deviceId,
						that.startNotice(that.uuid)
						that.getdata = ''
					},
					fail() {
						uni.showToast({
							icon: 'none',
							title: '获取特征值失败'
						})
					}
				})
			},
			// 启用 notify 功能
			startNotice(e) {
				let that = this
				uni.notifyBLECharacteristicValueChange({
					state: true, // 启用 notify 功能
					deviceId: e.deviceId,
					serviceId: e.serviceId,
					characteristicId: e.notifyId,
					success(res) {
						console.log('启用 notify 功能', res)
						//监听设备发送数据
						uni.onBLECharacteristicValueChange((sjRes) => {
							uni.showToast({
								title: '连接中',
								icon: 'loading'
							})
							that.getdata = that.ab2hex(sjRes.value)
							console.log('监听设备发送数据', that.getdata)
							if(sjRes.value){
								setTimeout(()=>{
									uni.hideToast();
								},1000)
							}
						})
					},
					fail() {
						console.log('启用 notify 功能失败')
					}
				})
			},
			// 写入数据
			sendMy(str) {
				let that = this
				//转换数据格式
				uni.writeBLECharacteristicValue({
					deviceId: that.uuid.deviceId, // 蓝牙设备 deviceId
					serviceId: that.uuid.serviceId, // 蓝牙服务uuid,
					characteristicId: that.uuid.writeId, // 蓝牙特征 writeId
					value: str, // 这里的value是ArrayBuffer类型
					writeType: 'write',
					success(res) {
						console.log('指令下发成功', res)
						
					},
					fail(err) {
						console.log('指令发送失败', err)
					}
				})
			},
			stringToHex(str) {
			  let hex = "";
			  for (let i = 0; i < str.length; i++) {
			    let charValue = str.charCodeAt(i).toString(16);
			    hex += charValue.length < 2 ? "0" + charValue : charValue;
			  }
			  return hex;
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			string2buffer(str) {
				let val = ""
				if (!str) return;
				let length = str.length;
				let index = 0;
				let array = []
				while (index < length) {
					array.push(str.substring(index, index + 2));
					index = index + 2;
				}
				val = array.join(",");
				// 将16进制转化为ArrayBuffer
				return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16)
				})).buffer
			},
			// 断开连接
			cancelConcent(e) {
				let that = this
				if (that.device.deviceId !== '--') {
					uni.closeBLEConnection({
						deviceId: that.device.deviceId,
						success(res) {
							console.log(' 断开连接成功', res)
						},
						fail(err) {
							console.log(' 断开连接失败', err)
						},
					})
				}
			},
			showWifi(){
				this.$refs.wifiSet.openModel()
			},
			unbindBtn(){
				this.$refs.unbind.openModel()
			},
			bindChange(){
				this.getlist()
			},
			getwifiInfo(data){
				console.log(data)
				let info = data +','+ this.ips
				let hexData = this.stringToHex(info)
				let buffer = this.string2buffer(hexData);
				console.log(info)
				this.sendMy(buffer)
			},
			async getFw(){
				let res = await this.http('get','/system/dict/data/type/tc_server')
				let sIp=''
				let mIp=''
				if(res.code==200){
					res.data.forEach(item=>{
						if(item.dictLabel=='tcServerIP'){
							sIp=item.dictValue
						}
						if(item.dictLabel=='mqttServerIP'){
							mIp=item.dictValue
						}
					})
					this.ips = sIp+','+mIp
				}
			},
			startBtn(){
				let that=this
				if(this.sbIszx=='0'){
					this.toast('设备离线中')
				}else{
					const formData={
						ope: 'A',
						pid: this.pid,
						nmn:this.nmn,
						qid:this.isGl
					}
					const result = this.sbIp.replace(/^(.*?):.*$/, (match, group1) => group1 || this.sbIp);
					uni.request({
						url: 'http://'+result+':8000', //仅为示例，并非真实接口地址。
						data: formData,
						header:{
							'content-type':'application/x-www-form-urlencoded'
						},
						method:'post',
						success: (res) => {
							console.log(res.data);
							if(res.data.status=='success'){
								that.toast('开启成功')
							}
						}
					});
				}
			},
			async getTc(){
				let res = await this.http("get","/tc/tcOperate/getTcqueueList")
				console.log(res)
				if(res.code==200){
					res.data.forEach(item=>{
						if(item.status=='1'){
							this.qid = item.id
						}
					})
					let res1 = await this.http("get","/tc/tcOperate/tcQueueStudentList",{
						pageNum: 1,
						pageSize: 10,
						queueid: res.data[0].id
					})
					this.nmn = res1.total
				}
			},
			async getlist(){
				let res = await this.http("get","/tc/project/list",{pageNum:1,pageSize:10})
				if(res.code==200){
					this.typeData = res.rows
				}
				this.getSb()
			},
			async editItem(item){
				let list = [{sbid:this.eqId,projectid:item.id}]
				let res = await this.http("put","/tc/shebei",{id:this.eqId,shebeiProjectList:list})
				if(res.code==200){
					this.toast('编辑成功')
					this.getSb()
				}
			},
			async getSb(){
				let res = await this.http("get","/tc/shebei/list",{
					pageNum:1,
					pageSize:15,
					sbXxid:'200',
					sbClientid:''
				})
				if(res.code==200){
					res.rows.forEach(item=>{
						if(item.id==this.eqId){
							this.sbIp = item.sbIp
							this.sbIszx = item.sbIszx
							this.sbClientid = item.sbClientid
							this.initBlue()
							if(item.shebeiProjectList.length>0){
								this.isGl = item.shebeiProjectList[0].projectid
							}else{
								this.isGl = ''
							}
						}
					})
				}
			},
			gotoPage(e){
				if(this.sbIszx=='1'){
					uni.navigateTo({
						url: e
					})
				}else{
					this.toast('设备离线中')
				}
			}
		}
	}
</script>

<style lang="less">
	.wifi-box{
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40upx;
		box-sizing: border-box;
		border-radius: 20upx;
		background: url('/static/images/bg3.png') no-repeat;
		background-size: 100% 100%;
		box-shadow: 0upx 8upx 8upx 0upx rgba(0, 0, 0, 0.14);
		margin-bottom: 30upx;
		.wifi-l{
			display: flex;
			align-items: center;
			image{
				width: 60upx;
				height: auto;
			}
			.wifi-text{
				margin-left: 20upx;
				text{
					display: block;
					font-size: 32upx;
					&:last-child{
						font-size: 24upx;
						color: #999;
					}
				}
			}
		}
		.jt-icon{
			width: 40upx;
			height: auto;
		}
	}
	.sb-info{
		width: 100%;
		padding: 20upx 0;
		box-sizing: border-box;
	}
	.pro-box{
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		.active{
			background-color: #76A1F6 !important;
			color: #fff;
			image{
				filter: brightness(0%) invert(100%) !important;
				-webkit-filter: brightness(0%) invert(100%) !important;
			}
		}
		.pro-item{
			width: 31%;
			margin: 10upx 1.15%;
			background-color: #EDF1FA;
			text-align: center;
			padding: 20upx 0;
			box-sizing: border-box;
			border-radius: 8upx;
			image{
				width: 40upx;
				height: auto;
				filter: brightness(0%);
				-webkit-filter: brightness(0%);
			}
			text{
				display: block;
				font-size: 28upx;
			}
		}
	}
	.set-box{
		width: 100%;
		border-radius: 20upx;
		background: #F8F9FA;
		box-shadow: 0upx 8upx 8upx 0upx rgba(0, 0, 0, 0.14);
		display: flex;
		align-items: center;
		justify-content: space-around;
		padding: 20upx;
		box-sizing: border-box;
		margin-top: 20upx;
		.set-item{
			width: 30%;
			text-align: center;
			image{
				width: 100upx;
				height: auto;
			}
			text{
				display: block;
				font-size: 28upx;
			}
		}
	}
</style>